package servlet;

import user.Member;
import user.Register;
import util.DBUtilDao;
import util.MD5;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class RegServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        MD5 md5 = new MD5();
        String password1 = md5.getMD5String(request.getParameter("password1"));//表单第一个密码，采用MD5加密算法获取密文
        String password2 = md5.getMD5String(request.getParameter("password2"));//表单第二个密码，采用MD5加密算法获取密文
        if (username.equals("")) {
            request.setAttribute("phoneErrorMessage", "手机号不能为空！");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        } else if (password1.equals(md5.getMD5String(""))) { //空串也会被加密
            request.setAttribute("password1ErrorMessage", "密码不能为空！");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        } else if (password2.equals(md5.getMD5String(""))) {//空串也会被加密
            request.setAttribute("password2ErrorMessage", "确认密码不能为空！");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        } else if (!(password1.equals(password2))) {
            request.setAttribute("password2ErrorMessage", "密码不一致！");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        }else {
            DBUtilDao dbUtilDao = new DBUtilDao();
            //查询数据表register，如果用户名已存在，则不允许注册
            List<Register> list= null;
            try {
                list = dbUtilDao.getRegister(username);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            if(list!=null&&list.size()>0){
                request.setAttribute("regErrorMessage","用户名已存在");
                try {
                    dbUtilDao.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                request.getRequestDispatcher("reg.jsp").forward(request, response);
            }else {
                Register register = new Register(username, password1); //使用手机号和加密后的密码创建对象

                try {
                    dbUtilDao.addOne(register);//添加到数据库
                    dbUtilDao.close();//释放资源
                    response.sendRedirect("login.jsp");
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }

    }
}
